import { Component, OnInit } from "@angular/core";
import { NzNotificationService } from "ng-zorro-antd";
import { Router } from "@angular/router";
import { HttpServcie } from "../../../service/http.service";
import { Config } from "../../../service/config";
import { NoticeBean } from "../bean/notice.bean";
import { el } from "@angular/platform-browser/testing/src/browser_util";
import { NzModalService, NzModalSubject } from "ng-zorro-antd";
import * as moment from "moment";

@Component({
  selector: "notice-page",
  templateUrl: "notice.html",
  styleUrls: ["notice.scss"]
})
export class NoticePage implements OnInit {
  config = Config;
  constructor(
    private httpServcie: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService,

  ) {}
  //接收参数
  noticeBean: NoticeBean = new NoticeBean();
  //返回的集合
  list: any = [];
  //总页数
  total: string = "0";
  //多选框
  allChecked: any = false;
  //多选框
  indeterminate: any = false;
  //设置add的
  isAddVisible = false;
  isAddConfirmLoading = false;
  inValue: string;
  currentModal: NzModalSubject;
  isConfirmLoading = false;
  isRead: string;
  updateData: any = {};
  modal: any = 0;
  totalList: any = [];
  searchOptions: any = [];
  sureDel = false;
  picList: Array<string>;
  isJG = false;
  _startDate = null;
  _endDate = null;
  isSend: boolean = false;
  newArray = len => {
    const result = [];
    for (let i = 0; i < len; i++) {
      result.push(i);
    }
    return result;
  };
  _startValueChange = () => {
    if (this._startDate > this._endDate) {
      this._endDate = null;
    }
  };
  _endValueChange = () => {
    if (this._startDate > this._endDate) {
      this._startDate = null;
    }
  };
  _disabledStartDate = startValue => {
    if (!startValue || !this._endDate) {
      return false;
    }
    return startValue.getTime() >= this._endDate.getTime();
  };
  _disabledEndDate = endValue => {
    if (!endValue || !this._startDate) {
      return false;
    }
    return endValue.getTime() <= this._startDate.getTime();
  };
  get _isSameDay() {
    return (
      this._startDate &&
      this._endDate &&
      moment(this._startDate).isSame(this._endDate, "day")
    );
  }
  get _endTime() {
    return {
      nzHideDisabledOptions: true,
      nzDisabledHours: () => {
        return this._isSameDay ? this.newArray(this._startDate.getHours()) : [];
      },
      nzDisabledMinutes: h => {
        if (this._isSameDay && h === this._startDate.getHours()) {
          return this.newArray(this._startDate.getMinutes());
        }
        return [];
      },
      nzDisabledSeconds: (h, m) => {
        if (
          this._isSameDay &&
          h === this._startDate.getHours() &&
          m === this._startDate.getMinutes()
        ) {
          return this.newArray(this._startDate.getSeconds());
        }
        return [];
      }
    };
  }

  ngOnInit() {
    this.noticeBean.pageSize = 10;
    this.noticeBean.currentPage = 1;
    this.noticeBean.currentUserId = JSON.parse(window.localStorage["user"]).id;
    this.isJG = JSON.parse(window.localStorage["user"]).partyType == "4";
    if (this.isSend) {
      this.querySend();
    } else {
      this.query();
    }
  }

  querySend() {
    this.isSend = true;
    this.noticeBean.startTime = this._startDate
      ? moment(this._startDate).format("YYYYMMDDHHmmss")
      : "";
    this.noticeBean.endTime = this._endDate
      ? moment(this._endDate).format("YYYYMMDDHHmmss")
      : "";
    this.noticeBean.isRead = this.isRead;

    this.httpServcie.getSendNoticeList(this.noticeBean).subscribe(
      data => {
        if (data.status === 200) {
          this.list = data.data.list;
          this.total = data.data.total;
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }
  //查询
  query() {
    this.isSend = false;
    this.noticeBean.startTime = this._startDate
      ? moment(this._startDate).format("YYYYMMDDHHmmss")
      : "";
    this.noticeBean.endTime = this._endDate
      ? moment(this._endDate).format("YYYYMMDDHHmmss")
      : "";
    this.noticeBean.isRead = this.isRead;

    this.httpServcie.getNoticeList(this.noticeBean).subscribe(
      data => {
        if (data.status === 200) {
          this.list = data.data.list;
          this.total = data.data.total;
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }

  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };

  //table加载数据时
  displayDataChange($event) {
    this.list = $event;
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.list.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.list.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //全选
  checkAll(value) {
    if (value) {
      this.list.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.list.forEach(data => (data.checked = false));
    }
  }

  //分页
  nzPageSizeChange(event) {
    this.noticeBean.pageSize = event;
    this.noticeBean.currentPage = 1;
    if (this.isSend) {
      this.querySend();
    } else {
      this.query();
    }
  }

  //输入框的方法
  nzPageIndexChange(event) {
    this.noticeBean.currentPage = event;
    if (this.isSend) {
      this.querySend();
    } else {
      this.query();
    }
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.noticeBean.currentPage = event;
    if (this.isSend) {
      this.querySend();
    } else {
      this.query();
    }
  }

  detailNotification(data) {
    this._notification.blank(data.title, data.content);
    //确认已读，修改状态
    if (this.isSend) {
      return;
    }

    //如果是维保完成通知，pc端不去 变成已读状态
    data.isRead = "1";
    let params = {
      isRead: "1",
      id: data.id
    };
    let ob = this.httpServcie.updateReadState(params);
    ob.subscribe(data => {
      console.log(data);
    });

  }

  /**
   * 已由图片附件，修改为文本文件
   * @param titlepic
   * @param contentpic
   * @param footerpic
   * @param param
   */
  showImage(titlepic, contentpic, footerpic, param) {
    if (param == null || param == "") {
      this._notification.create("warning", "提示", "附件不存在！");
      return;
    }
    this.picList = param.split(",");
    this.currentModal = this.modalService.open({
      title: titlepic,
      content: contentpic,
      footer: footerpic,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  show(param){
    this.download(param,"附件.doc");
  }
  download(url, name) {
    let link = document.createElement('a');
    let body = document.querySelector('body');

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(blob => {
      link.href = window.URL.createObjectURL(blob);
      link.download = name;
      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    });
  }
  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }
}
